#include "TestWrapper.h"

// implementation code of WrapperFactory - do NOT modify the next 5 lines
AbstractWrapper* WrapperFactory::wrapper = 0;
AbstractWrapper* WrapperFactory::createWrapper() {
  if (wrapper == 0) wrapper = new TestWrapper;
  return wrapper;
}
// Do not modify the following line
volatile bool TestWrapper::GlobalStop = false;

// a default constructor
TestWrapper::TestWrapper() {
  // create any objects here as instance variables of this class
	ast = AST::getInstance();
  // as well as any initialization required for your spa program
}

// method for parsing the SIMPLE source
void TestWrapper::parse(std::string filename) {
	// call your parser to do the parsing
	Parser2 p = Parser2();
	p.parse(filename);
	// ...rest of your code...
	DesignExtractor DesExt = DesignExtractor();
	DesExt.fillTable();
}

// method to evaluating a query
void TestWrapper::evaluate(std::string query, std::list<std::string>& results){
// call your evaluator to evaluate the query here
  // ...code to evaluate query...
	splitQuery(query, results);

  // store the answers to the query in the results list (it is initially empty)
  // each result must be a string.
}

void TestWrapper::splitQuery(std::string query, std::list<std::string>& results){
	int pos;
	std::string tempQuery, declPart, queryPart;
	char* tempLower;

	tempLower = new char [query.size()+1];
	strcpy (tempLower, query.c_str());

	for(int i=0;tempLower[i]!='\0';i++)
		if(isalpha(tempLower[i]))
			tempLower[i]=tolower(query.at(i));

	tempQuery = tempLower;
	pos=tempQuery.find("select");

	results.clear();

	if(pos!=-1 && !query.empty())
	{
			declPart=query.substr(0,pos-1);
			queryPart=query.substr(pos, query.length()-1);
			SplitDeclaration SpDc; 
			QueryEvaluator obj;
			QRYSTATEMENT_TYPE asstType;
			asstType=SpDc.splitDeclaration(obj, declPart,list);
			int isValidQuery;

			boost::trim(queryPart);
			
			if(asstType!=_INVALID)
			{
				results.clear();
				isValidQuery = obj.validateQuery(queryPart, results);

				if(isValidQuery>=0)
				{
					try {
							obj.executeQuery(results);
					}
					catch (char* error) {
						cout <<"Error reported: " << error << endl;			
					}
	
					if(AbstractWrapper::GlobalStop)
					{
						results.clear();
						return;
					}
				}

			}
	}
}